package com.xy.modular.basics.action;

import com.xy.framework.base.controller.BaseController;
import com.xy.framework.mreturn.MReturnObject;
import com.xy.framework.pager.PageRequest;
import com.xy.framework.pager.SearchCondition;
import com.xy.framework.util.DateUtils;
import com.xy.framework.util.JsonPropertyEditor;
import com.xy.framework.util.uuid.UUIDUtils;
import com.xy.modular.basics.entity.user.User;
import com.xy.modular.basics.entity.user.UserAuthLocal;
import com.xy.modular.basics.entity.user.UserDep;
import com.xy.modular.basics.service.IDepService;
import com.xy.modular.basics.service.IUserDepService;
import com.xy.modular.basics.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
	@Resource
	private IDepService depService;
	@Autowired
	private IUserService userService;

	@Autowired
	private IUserDepService userDepService;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class,
				new CustomDateEditor(new SimpleDateFormat(DateUtils.DATETIME_SECOND_FORMAT), true));
		binder.registerCustomEditor(User.class, new JsonPropertyEditor(User.class, true));
	}

	@RequiresRoles("SYSTEMER")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public @ResponseBody MReturnObject List(HttpServletRequest request, User user, UserDep userDep) {
		PageRequest pageRequest = newPageRequest(request);
		pageRequest.setColumns(
				" basics_user.id,basics_user.name,basics_user.birthday,basics_user.real_name,basics_user.mobile,basics_user.join_Date,(CASE basics_user.sex WHEN 0 THEN '男' ELSE '女' END) AS sex, "
				+ 			"(SELECT GROUP_CONCAT(basics_dep.name) FROM basics_user_dep LEFT JOIN  basics_dep ON basics_user_dep.`dep_id`=basics_dep.id "
						+ "WHERE basics_user_dep.user_id = basics_user.id AND basics_user_dep.type=0) mainDepName,"
						+ "(SELECT GROUP_CONCAT(basics_dep.name) FROM basics_user_dep LEFT JOIN  basics_dep ON basics_user_dep.dep_id=basics_dep.id "
						+ "WHERE basics_user_dep.user_id = basics_user.id AND basics_user_dep.type=1 ) subDepName,"
						+ "(SELECT GROUP_CONCAT(basics_user_dep.dep_id) FROM basics_user_dep WHERE basics_user_dep.user_id = basics_user.id AND basics_user_dep.type=1) subDepIds,"
						+ "(SELECT GROUP_CONCAT(basics_user_dep.dep_id) FROM basics_user_dep WHERE basics_user_dep.user_id = basics_user.id AND basics_user_dep.type=0) mainDepIds");
		// pageRequest.addAndCondition(User.DEPID, SearchCondition.EQUAL,
		// user.getDepId());
		pageRequest.setLeftJoinSql(" LEFT JOIN basics_user_dep ON basics_user_dep.user_id=basics_user.id  "
				+ " LEFT JOIN basics_dep ON basics_user_dep.dep_id=basics_dep.id ");
		pageRequest.addAndCondition(UserDep.DEP_ID, SearchCondition.EQUAL, userDep.getDepId());
		return new MReturnObject(MReturnObject.SUCCESS, userService.findColumnsPageAll(pageRequest),
				userService.getCount(pageRequest));
	}

	@RequiresRoles("SYSTEMER")
	@RequestMapping(value = "/user/list", method = RequestMethod.GET)
	public @ResponseBody MReturnObject userList(HttpServletRequest request, User user, UserDep userDep) {
		PageRequest pageRequest = newPageRequest(request);
		return new MReturnObject(MReturnObject.SUCCESS, userService.findAll(pageRequest));
	}

	@RequiresRoles("SYSTEMER")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public @ResponseBody MReturnObject save(User user, String birthdays, UserAuthLocal userAuthLocal, UserDep userDep,
			HttpServletRequest request) {
		if (birthdays != null || !birthdays.endsWith("")) {
			user.setBirthday(DateUtils.parseDate(birthdays));
		}
		PageRequest pageRequest = new PageRequest();
		pageRequest.addOrCondition(User.NAME, SearchCondition.EQUAL, user.getName());
		if (userService.findAll(pageRequest).size() > 0) {
			return new MReturnObject(MReturnObject.ERROR, "昵称重复！");
		}
		pageRequest.addOrCondition(User.REALNAME, SearchCondition.EQUAL, user.getRealName());
		if (userService.findAll(pageRequest).size() > 0) {
			return new MReturnObject(MReturnObject.ERROR, "真实姓名重复！");
		}
		pageRequest.addOrCondition(User.MOBILE, SearchCondition.EQUAL, user.getMobile());
		if (userService.findAll(pageRequest).size() > 0) {
			return new MReturnObject(MReturnObject.ERROR, "手机号重复！");
		}
		user.setId(UUIDUtils.UUIDNumber());
		user.setUserType("1");

		userService.save(user, userAuthLocal);
		String mainDep = request.getParameter("mainDep");
		if (depService.getById(mainDep) != null) {
			userDepService.save(new UserDep(UUIDUtils.UUIDNumber(), user.getId(), mainDep, 0));
		}
		String subDep = request.getParameter("subDep");
		if (subDep != null) {
			for (int i = 0; i < subDep.split(",").length; i++) {
				if (depService.getById(subDep.split(",")[i]) != null) {
					userDepService.save(new UserDep(UUIDUtils.UUIDNumber(), user.getId(), subDep.split(",")[i], 1));
				}
			}
		}

		return new MReturnObject(MReturnObject.SUCCESS, user);
	}

	/**
	 * 冻结
	 * 
	 * @param user
	 * @return
	 */
	@RequiresPermissions("user:free")
	@RequestMapping(value = "/free", method = RequestMethod.POST)
	public @ResponseBody MReturnObject free(User user) {
		user.setAvatar("1");
		userService.update(user);
		return new MReturnObject(MReturnObject.SUCCESS, userService.findAll());
	}

	/**
	 * 解冻
	 * 
	 * @param user
	 * @return
	 */
	@RequiresPermissions("user:thaw")
	@RequestMapping(value = "/thaw", method = RequestMethod.POST)
	public @ResponseBody MReturnObject thaw(User user) {
		user.setAvatar("0");
		userService.update(user);
		return new MReturnObject(MReturnObject.SUCCESS, userService.findAll());
	}

	/**
	 * 修改
	 * 
	 * @param user
	 * @return
	 */
	@SuppressWarnings("null")
	@RequiresRoles("SYSTEMER")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public @ResponseBody MReturnObject update(User user, String birthdays, UserAuthLocal userAuthLocal) {
		if (birthdays != null || !birthdays.endsWith("")) {
			user.setBirthday(DateUtils.parseDate(birthdays));
		}
		//user.setId(UUIDUtils.UUIDNumber());
		User u2=userService.getById(user.getId());
		u2.setName(user.getName());
		u2.setRealName(user.getRealName());
		u2.setBirthday(user.getBirthday());
		u2.setSex(user.getSex());
		u2.setJoinDate(user.getJoinDate());
		u2.setAvatar(user.getAvatar());
		u2.setMobile(user.getMobile());
		userService.update(u2);
		return new MReturnObject(MReturnObject.SUCCESS, userService.findAll());
	}

	/**
	 * 删除
	 * 
	 * @param user
	 * @return
	 */
	@RequiresPermissions("user:dele")
	@RequestMapping(value = "/dele", method = RequestMethod.POST)
	public @ResponseBody MReturnObject dele(User user) {
		userService.deleteById(user.getId());
		return new MReturnObject(MReturnObject.SUCCESS, MReturnObject.SUCCESS);
	}
}
